<template>
    <div>
        <el-dialog
        title="添加分类"
        :visible.sync="centerDialogVisible"
        width="80%"
        @close="closeDialog">
        <div class="Main">
            <el-form :model="typeForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="分类名称" prop="catName">
                    <el-input v-model="typeForm.catName"></el-input>
                </el-form-item>
                <el-form-item label="分类说明" prop="memo">
                    <el-input type="textarea" v-model="typeForm.memo" :autosize="{minRows: 7}"></el-input>
                </el-form-item>
                <el-form-item prop="attr" lebel-position="right" class="custom-checkbox" >
                    <template>
                        <div class="content">
                        <el-checkbox v-model="isCheck"></el-checkbox>
                        <span>分类属性</span>
                        </div>
                    </template>
                    
                </el-form-item>
                <el-card shadow="never" body-style="{border:1px solid black}" v-show="isCheck == true" style="height: 300px;">
                <el-button type="primary" @click="addPrimary" class="addPrimary">+ 一级属性</el-button>
                <el-table 
                class="main-table"
                :data="inputForm"
                row-key="name"
                :row-style="{'height':'54px'}"
                lazy
                default-expand-all
                @cell-click="tabClick"
                @cell-mouse-enter="tabClick"
                @cell-mouse-leave="inputBlur"
                :row-class-name="tableRowClassName"
                :cell-class-name="tableCellClassName"
                :tree-props="{children: 'addDetailDTOS', hasChildren: 'addDetailDTOS'}"
                style="width: 100%;margin-top: 40px;">
                <el-table-column prop="name" label="属性名称" width="280" header-align="left"> 
                    <template slot-scope="scope">
                        <span :class="{'name-position':!scope.row.addDetailDTOS}">
                        <span v-if="scope.row.index === clickRow && scope.column.index === clickCell &&!(scope.row.parentFlag||scope.row.childrenFlag)" class="input-index">
                            <el-input
                            ref="editInput"
                            v-model="data_change"
                            maxlength="50"
                            size="mini"
                            @blur="inputBlur"
                            />
                        </span>
                        <span v-else>{{ scope.row.name }}
                           <span v-if="scope.row.parentFlag" class="ParentFlag">来源于父节点</span> 
                        </span>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="录入方式" class="input-mathode" width="200px">
                    <template slot-scope="scope" >
                        <el-select v-model="scope.row.inputType" placeholder="请选择" size="small" v-if="!scope.row.addDetailDTOS"  style="margin-bottom: 15px;">
                            <el-option v-for="item in option" :label="item.label" :value="item.value" :key="item.value"/>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="选取类型" width="240px">
                    <template slot-scope="scope">
                    <el-radio-group v-model="scope.row.selectType" v-if="!scope.row.addDetailDTOS">
                        <el-radio :label="0">唯一</el-radio>
                        <el-radio :label="1">单选</el-radio>
                        <el-radio :label="2">多选</el-radio>
                    </el-radio-group>
                    </template>
                </el-table-column>
                <el-table-column prop="canAdd" label="允许添加">
                    <template slot-scope="scope">
                        <span>
                        <el-switch v-model="scope.row.handAddStatus" active-color="#67c23a" :active-value="1"
                        :inactive-value="0" v-if="!scope.row.addDetailDTOS">
                        </el-switch>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="attribute" label="属性值">
                    <template slot-scope="scope">
                        <span v-if="!scope.row.addDetailDTOS">
                        <span v-if="scope.row.index === clickRow && scope.column.index === clickCell" class="input-index">
                            <el-input
                            ref="editInput"
                            v-model="scope.row.inputList"
                            maxlength="50"
                            size="mini"
                            @blur="inputBlur"
                            />
                        </span>
                        <span v-else>{{ scope.row.inputList }}</span>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="operate" label="操作" width="150px">
                    <template slot-scope="scope">
                        <div class="controller">
                        <span v-show="scope.row.addDetailDTOS" @click="addChild(scope.$index,scope.row)">
                            <span class="con_div_span">+子属性</span>
                        </span>
                        <span @click="del(scope.$index,scope.row)" v-show="scope.row.addDetailDTOS&&!scope.row.parentFlag">
                            <span class="con_div_span">删除</span>
                        </span>
                        <span @click="del(scope.$index,scope.row)" v-show="!scope.row.addDetailDTOS&&!scope.row.childrenFlag">
                            <span class="con_div_del">删除</span>
                        </span>
                        </div>
                    </template>
                </el-table-column>
                </el-table>
                </el-card>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
import { getQuery,addcategory } from '@/api/api.js'
  export default {
    props:{
        dialogVisible: {
            type: Boolean,
            default: false
        },
        parentId:{
            type: String,
            default: '-1'
        }
    },
    data() {
      return {
        data_change:"", // 保存name值的修改
        clickRow: null, // 当前点击的行
        clickCell: null, // 当前点击的列
        option:[
            {
                value: 1,
                label: '从属性中获取'
            }, 
            {
                value: 0,
                label: '手工录入'
            }
        ],
        isCheck:false,
        isAddONE:false,
        centerDialogVisible: this.dialogVisible,
        parentForm:[],
        inputForm:[],
        typeForm:{
            "attributeAddDTOS": [
            ],
            "catName": "",
            "memo": "",
            "parentId": -1
        }
      };
    },
    watch:{
        async dialogVisible(newVal) {
            this.centerDialogVisible = newVal;
            if(newVal&&this.parentId!=-1){
               return await this.getList(this.parentId) 
            }  
        },
        parentId(id){
            this.typeForm.parentId = id
        }
        
    },
    methods:{
        async getList(CatName){
            try{
                // console.log(CatName);
                const list = await getQuery(CatName)
                if(list.data.code == 200) {
                    // console.log("1111");
                    // console.log(list.data.result.categoryTypVOList);
                    this.parentForm = list.data.result.categoryTypVOList;
                    this.parentForm.forEach(elem=>{
                        let addDetailDTOS = elem.categoryAttributeListVOList;
                        delete elem.categoryAttributeListVOList;
                        this.$set(elem,'addDetailDTOS',addDetailDTOS)
                        // elem.addDetailDTOS = addDetailDTOS;
                        elem.addDetailDTOS.forEach(val=>{
                            val.childrenFlag = true
                        })
                        elem.parentFlag = true   // 表示父类属性
                        console.dir(elem)
                        
                    })
                    if(this.parentForm.length!==0){
                        this.isCheck = true;
                        this.inputForm = this.parentForm
                    }
                    console.log("===>");
                    console.log(this.inputForm);
                }
            }catch(error){
                console.log(error)
            }
        },
        closeDialog() {
            // 当点击关闭按钮时，更新本地数据并发出事件通知父组件  
            this.centerDialogVisible = false;
            this.inputForm = [];
            this.typeForm.catName = ""
            this.typeForm.memo = ""
            this.typeForm.parentId = -1
            this.parentId = -1
            this.isCheck = false
            this.$emit('update', false);
        },
        del(index,row){
            console.log("index:"+index)
            let parent_num = 0,children_num=0,tag=0; // parent_num 父循环 tag 子循环次数
            for(let elem of this.inputForm) {
                if (index==elem.index) {
                    return this.inputForm.splice(index-children_num,1)
                }
                for(let val of elem.addDetailDTOS){
                    tag++;
                    if (index==val.index) {
                       return this.inputForm[parent_num].addDetailDTOS.splice(index-(parent_num+1)-(children_num),1); 
                    } 
                }
                children_num+=tag;
                tag = 0;
                parent_num++;
            }
            this.$message({
                message: "删除成功",
                type: 'success'
            });
        },
        async submit(){
            if(this.isCheck){
                this.typeForm.attributeAddDTOS = this.inputForm.filter(elem=>{
                    return elem.parentFlag!==true;
                })
            }
            try{
                const res = await addcategory(this.typeForm)
                if(res.data.code == 200){
                    this.$message({
                        message: "添加成功",
                        type: 'success'
                    });
                    this.$emit('comfirm')
                    this.closeDialog()
                }
            }catch(error){
                console.error("提交失败:", error);
            }
        },
        addPrimary(){
            this.isAddONE = true
            let obj = {
                    "addDetailDTOS": [
                    ],
                    "name": ""
                }
            this.inputForm.push(obj)
        },
        addChild(index,row){
            let obj = {
                    "handAddStatus": 0,
                    "inputList": "",
                    "inputType": "",
                    "name": "",
                    "selectType": 0,
                    "sort": 0
                }
            row.addDetailDTOS.push(obj);
        },
        tabClick(row, column, cell, event) {
            this.clickRow = row.index
            this.clickCell = column.index
            this.data_change = row.name
        },
        // 把每一行的索引放进row
        tableRowClassName({ row, rowIndex }) {
            row.index = rowIndex;
            return "del_row"
        },
    
        // 把每一列的索引放进column
        tableCellClassName({ column, columnIndex }) {
            column.index = columnIndex;
        },
    
        // 失去焦点初始化
        inputBlur(row, event, column) {
            this.clickRow = null;
            this.clickCell = null;
            row.name = this.data_change
        },
    },
  };
</script>

<style scoped>
.addPrimary{
    position: absolute;
    top:400px;
    right: 40px;
}
.main-table {
  height: 200px;
  flex:1;/*使内容区域填充剩余空间 */
  overflow-y:auto;/*当内容超出时显示滚动条*/
  scrollbar-width:thin;
}
/* 修改表树形结构 */
.el-table /deep/ .el-icon-arrow-right:before {
  content: ""
}

.name-position {
    display: inline-block;
    transform: translateX(50px);
}

/* .el-table /deep/ .el-table__row--level-1 .el-table__cell:nth-child(1) div:before{
    content: "";
    display: inline-block;
} */
/* //有子节点 且已展开 */
/* .el-table /deep/ .el-table__expand-icon--expanded {
  .el-icon-arrow-right:before {
    content: '';
  }
} */
/* //没有子节点 */
.el-tree /deep/.el-tree-node__expand-icon.is-leaf::before
.el-table /deep/.el-table__placeholder::before {
  content: '';
}
.el-table /deep/ .el-switch__core{
    border: 1px solid black;
}

.con_div_span {
    margin: 10px;
}
.con_div_del{
    margin-left: 60px;
}

.custom-checkbox /deep/ .content{
    /* background-color: aqua; */
    transform: translateX(-88px);
}
.custom-checkbox /deep/ .content span {
    margin-left: 10px;
}
.el-table  /deep/ .cell .el-select{
    /* transform: translateY(3px); */
    height:18px
}
/* .el-table  /deep/ .cell .el-select .el-input__suffix{ */
    /* transform: translateY(15px); */
    /* height:18px */
/* } */
.input-index {
    display: inline-block;
    width: 100px;
}
.ParentFlag {
    display: inline-block;
    width: 80px;
    background-color: red;
    color: white;
}
.del_row {
    display: none
}
</style>